package com.ihealthway.all.utils;


import com.ihealthway.all.groupbuy.vo.Reward;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * All project useful util methods collection
 *
 * @author 凡梦星尘(elkan1788@gmail.com)
 */
public class Utils {

    private static final Log logger = Logs.get();

    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMddHHmmss_SSS");
    private static final SimpleDateFormat DEF_SDF = new SimpleDateFormat("yyyyMMddHHmmss");

    // 放大倍数
    private static final int mulriple = 1000000;

    public static String replaceLogModuleName(String moduleName) {
        switch (moduleName) {
            case "system":
                moduleName = "系统配置";
                break;
            case "wechat":
                moduleName = "微信配置";
                break;
            case "shop":
                moduleName = "团购商城";
                break;
            case "user":
                moduleName = "用户信息";
                break;
        }
        return moduleName;
    }

    public static String replaceLogOperateType(String operateType) {
        switch (operateType) {
            case "add":
                operateType = "新增";
                break;
            case "update":
                operateType = "更新";
                break;
            case "delete":
                operateType = "删除";
                break;
            case "query":
                operateType = "查询";
                break;
        }
        return operateType;
    }

    public static String renameUploadFile(String fileName) {
        String fileSuf = fileName.substring(fileName.lastIndexOf("."));
        String newName = SDF.format(new Date())+ new Double((Math.random()*9+1)*100000).intValue() + fileSuf;
        return newName;
    }

    public static Date parseStr2Date(String date) {
        try {
            return DEF_SDF.parse(date);
        } catch (ParseException e) {
            logger.error("Parse string date to date object fail!!!", e);
        }
        return null;
    }

    public static Date parseStr2Date(String date, String fmt) {
        try {
            return new SimpleDateFormat(fmt).parse(date);
        } catch (ParseException e) {
            logger.error("Parse string date with fmt to date object fail!!!", e);
        }
        return null;
    }

    /**
     * 取出一个指定长度大小的随机正整数.
     *
     * @param length
     *            int 设定所取出随机数的长度。length小于11
     * @return int 返回生成的随机数。
     */
    public static int buildRandom(int length) {
        int num = 1;
        double random = Math.random();
        if (random < 0.1) {
            random = random + 0.1;
        }
        for (int i = 0; i < length; i++) {
            num = num * 10;
        }
        return (int) ((random * num));
    }

    /**
     * 获取当前时间 yyyyMMddHHmmss
     * @return String
     */
    public static String getCurrTime() {
        Date now = new Date();
        SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String s = outFormat.format(now);
        return s;
    }

    /**
     * 获取编码字符集
     * @param request
     * @param response
     * @return String
     */

    public static String getCharacterEncoding(HttpServletRequest request,
                                              HttpServletResponse response) {

        if(null == request || null == response) {
            return "utf-8";
        }

        String enc = request.getCharacterEncoding();
        if(null == enc || "".equals(enc)) {
            enc = response.getCharacterEncoding();
        }

        if(null == enc || "".equals(enc)) {
            enc = "utf-8";
        }

        return enc;
    }

    public static int luckLotteryDraw(List<Reward> rewards) {
        if (rewards!=null && !rewards.isEmpty()) {
            Reward reward = new Reward();
            reward.setRewardId(0);
            reward.setWeight(50);
            List<Reward> rewardsNew = new ArrayList<>();
            rewardsNew.add(reward);
            rewardsNew.addAll(rewards);

            List<Double> drawWeightList = new ArrayList<>();
            drawWeightList.add(20d);
            int rwdLen = rewardsNew.size();
            for (int i=1; i<rwdLen; i++) {
                double pr = (double) new Random().nextInt(30)+1;
                drawWeightList.add(pr);
            }
            LotteryUtil enterLot = new LotteryUtil(drawWeightList);
            int index = enterLot.randomColunmIndex();
            logger.infof("User win reward index: %d", index);
            if (rewardsNew.get(index) != null) {
                return rewardsNew.get(index).getRewardId();
            }
        }

        return 0;
    }


    //http://www.jb51.net/article/89791.htm
    public static int luckDraw(List<Reward> prizes) {

        Collections.shuffle(prizes);
        int ran = new Random().nextInt(prizes.size());
        if (prizes.get(ran).getRewardCount()>0) {
            return prizes.get(ran).getRewardId();
        }

        return -1;
        /*int lastScope = 0;
        // 洗牌，打乱奖品次序
        Collections.shuffle(prizes);
        Map<Integer, int[]> prizeScopes = new HashMap<>();
        Map<Integer, Integer> prizeQuantity = new HashMap<>();
        double chance = Double.valueOf(prizes.size()).doubleValue() / 100;
        DecimalFormat df = new DecimalFormat("#.00");
        BigDecimal probability = new BigDecimal(df.format(chance));
        for (Reward prize : prizes) {
            int prizeId = prize.getRewardId();
            // 划分区间
            int currentScope = lastScope + probability.multiply(new BigDecimal(mulriple)).intValue();
            prizeScopes.put(prizeId, new int[] { lastScope + 1, currentScope });
            prizeQuantity.put(prizeId, prize.getRewardCount());

            lastScope = currentScope;
        }

        // 获取1-1000000之间的一个随机数
        int luckyNumber = new Random().nextInt(mulriple);
        int luckyPrizeId = 0;
        // 查找随机数所在的区间
        if ((null != prizeScopes) && !prizeScopes.isEmpty()) {
            Set<Map.Entry<Integer, int[]>> entrySets = prizeScopes.entrySet();
            for (Map.Entry<Integer, int[]> m : entrySets) {
                int key = m.getKey();
                if (luckyNumber >= m.getValue()[0] && luckyNumber <= m.getValue()[1] && prizeQuantity.get(key) > 0) {
                    luckyPrizeId = key;
                    break;
                }
            }
        }

        return luckyPrizeId;*/
    }
}
